package com.ctparking;


import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Calendar;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.ctparking.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class Main extends Activity{

	static boolean noConnection = false;
	
	public boolean onKeyDown(int keyCode, KeyEvent event) {
	    if ((keyCode == KeyEvent.KEYCODE_BACK)) {
	    	startActivity(new Intent(Main.this, Main.class));
	        return true;
	    }
	    return super.onKeyDown(keyCode, event);
	}
	
	public static String parseISToString(InputStream is){
		  java.io.DataInputStream din = new java.io.DataInputStream(is);
		  StringBuffer sb = new StringBuffer();
		  try{
		   String line = null;
		   while((line=din.readLine()) != null){
		    sb.append(line+"\n");
		   }
		  }catch(Exception ex){
		   ex.getMessage();
		  }finally{
		   try{
		    is.close();
		   }catch(Exception ex){}
		  }
		  return sb.toString();
		 }
	
	public DefaultHttpClient getClient() {
		
	    DefaultHttpClient ret = null;
	    
	    
	    //SETS UP PARAMETERS
	
	    HttpParams params = new BasicHttpParams();
	    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
	    HttpProtocolParams.setContentCharset(params, "utf-8");
	    params.setBooleanParameter("http.protocol.expect-continue", false);
	
	    //REGISTERS SCHEMES FOR BOTH HTTP AND HTTPS
	
	    SchemeRegistry registry = new SchemeRegistry();
	    registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 8080));
	    final SSLSocketFactory sslSocketFactory = SSLSocketFactory.getSocketFactory();
	    sslSocketFactory.setHostnameVerifier(SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
	    registry.register(new Scheme("https", sslSocketFactory, 443));
	    ThreadSafeClientConnManager manager = new ThreadSafeClientConnManager(params, registry);
	    ret = new DefaultHttpClient(manager, params);
	
	    return ret;
	}
	
	public ArrayList<Parcheggio> getParkingList(String URL){
		ArrayList<Parcheggio> p_list = new ArrayList<Parcheggio>();
		int icon_pari = 0;
		int icon_dispari = 0;
		try {
      	HttpClient httpclient = this.getClient();  
      	HttpGet method = new HttpGet(URL);    
      	HttpResponse res = httpclient.execute(method); 
      	InputStream data = res.getEntity().getContent();
   	   	String result = parseISToString(data);
   	   	JSONArray jarray = new JSONArray(result);
   	   	
   	   	for(int i = 0; i<jarray.length(); i++){
   	   		p_list.add(new Parcheggio((JSONObject)jarray.getJSONObject(i)));
   	   		
   	   			if ((i+1) % 2 == 0){
   	   				if (icon_pari == R.drawable.parking_yellow)
   	   					icon_pari = R.drawable.parking_green;
   	   				else
   	   					icon_pari = R.drawable.parking_yellow;
   	   				
   	   				p_list.get(i).setIcon(icon_pari);
   	   			}
   	   			else
   	   			{
   	   				if (icon_dispari == R.drawable.parking2)
	   					icon_dispari = R.drawable.parking_red;
	   				else
	   					icon_dispari = R.drawable.parking2;
	   				
	   				p_list.get(i).setIcon(icon_dispari);
   	   			}
   	   	}
   	   	
      } catch (ClientProtocolException e) {
          e.printStackTrace();
          return p_list;
      } catch (IOException e) {  
          e.printStackTrace();
          return p_list;
      } catch (JSONException e) {
          e.printStackTrace();
          return p_list;
      } catch (Exception e){
          e.printStackTrace();
    	  return p_list;
      }
		
      //httpclient.getConnectionManager().shutdown(); 
		
		return p_list;
	}

	public void aggiornaFile(){
		Context c = this.getApplicationContext();
		try{
			
			Calendar cal = Calendar.getInstance();
			FileInputStream fis = c.openFileInput("Prenotazioni.txt");
			InputStreamReader isr = new InputStreamReader(fis);
			BufferedReader br = new BufferedReader(isr); 
			ArrayList<String> array_str = new ArrayList<String>();
			
			String riga = null;
			String[] s = null;
			while((riga = br.readLine()) != null){
				
				s = riga.split(";");
				String[] data = s[1].split("/");
				
				if(Integer.parseInt(data[0]) == cal.get(Calendar.DAY_OF_MONTH) && Integer.parseInt(data[1]) == (cal.get(Calendar.MONTH) + 1) && Integer.parseInt(data[2]) == cal.get(Calendar.YEAR)){
					
					String[] orario = s[3].split(":");
					
					int minuti_file = Integer.parseInt(orario[0]) * 60 + Integer.parseInt(orario[1]);		
					int minuti = cal.get(Calendar.HOUR) * 60 + cal.get(Calendar.MINUTE);
					int diff = minuti - minuti_file;
					
					if(diff < 60){
						array_str.add(riga);
					}
				}	
			}
			br.close();
			c.deleteFile("Prenotazioni.txt");
			int size = array_str.size();
			if(size > 0){
				FileOutputStream fos = c.openFileOutput("Prenotazioni.txt", Context.MODE_PRIVATE|Context.MODE_APPEND);
				OutputStreamWriter osw = new OutputStreamWriter(fos);
				BufferedWriter bw = new BufferedWriter(osw);
				
				for(int i = 0; i < size; i++ )
					bw.write(array_str.get(i)+"\n");
				bw.flush();
				bw.close();
			}
			else{
				FileOutputStream fos = c.openFileOutput("Prenotazioni.txt", Context.MODE_PRIVATE|Context.MODE_APPEND);
				fos.close();
			}
			
		}catch(FileNotFoundException e){
			e.printStackTrace();
		}catch(IOException e){
			e.printStackTrace();
		}
	}

    @Override
    public void onCreate(Bundle savedInstanceState) {
    	 super.onCreate(savedInstanceState);
        int orientation=getResources().getConfiguration().orientation;
    	if (orientation == 1) {
            // Portrait
            setContentView(R.layout.main);
        }
        else if (orientation == 2) {
            // Landscape
            setContentView(R.layout.landscape_main);
        }            
    
       // setContentView(R.layout.main);
    	Database.parkingList = new ArrayList<Parcheggio>();
        Database.parkingList = getParkingList(Database.ConnectionString);
	    //Database.parkingList = getParkingList("http://192.168.1.224:8182");
        noConnection = false;
        if (Database.parkingList.size() == 0)
        {
        	noConnection = true;
        //	Toast.makeText(this,"Verifica di essere connesso alla rete wi-fi o di avere una connessione dati attiva",Toast.LENGTH_LONG).show();
        }
	        aggiornaFile();
	        
	        Button entra = (Button)findViewById(R.id.btn_Go);
	        Button esci = (Button)findViewById(R.id.btn_esci);
	        Button prenotazioni = (Button)findViewById(R.id.btn_Prenotazioni);
	        Typeface font = Typeface.createFromAsset(getAssets(), "All_Caps.ttf");
	        entra.setTypeface(font);
	        esci.setTypeface(font);
	        prenotazioni.setTypeface(font);
	        entra.setOnClickListener(new View.OnClickListener() {
	        	
				@Override
				public void onClick(View v) {
					
					if(noConnection)
					{
						Toast.makeText(v.getContext(),"Verifica di essere connesso alla rete wi-fi o di avere una connessione dati attiva",Toast.LENGTH_LONG).show();
						startActivity(new Intent(Main.this , Main.class));
					}
					else
						startActivity(new Intent(Main.this , Parking.class));
				}
			});
	        
	        esci.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					
					AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
					builder.setMessage("Sei sicuro di voler uscire dall'applicazione?");
					       builder.setCancelable(false);
					       builder.setNegativeButton("NO", new DialogInterface.OnClickListener() {
					           public void onClick(DialogInterface dialog, int id) {
					           }
					       });
					       builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
					           public void onClick(DialogInterface dialog, int id) {
					        	   moveTaskToBack(true);
					           }
					       });
					builder.show();
				}
			});
	        
	        prenotazioni.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					
				startActivity(new Intent(Main.this , Prenotation.class));
					
				}
			});
    }
}